package com.example.tranport.client.destination;

import com.example.destination.JmsAnnoation;
import com.example.destination.JmsDestination;
import com.example.destination.JmsListener;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClientDestinationServiceImpl implements ClientDestinationService {

    private ApplicationContext applicationContext;

    @Override
    public ApplicationContext getApplicationContext() {
        return this.applicationContext;
    }

    public ClientDestinationServiceImpl(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /****
     * 用于客户端获取所有JMS的目的地信息
     * @return
     */
    @Override
    public List<JmsDestination> getDestinations() {
        List<JmsDestination> list = new ArrayList<>();
        Map<String, JmsListener> jmsListenerMap = getApplicationContext().getBeansOfType(JmsListener.class);
        for (String beanName : jmsListenerMap.keySet()) {
            JmsListener jmsListener = jmsListenerMap.get(beanName);
            if (jmsListener.getClass().isAnnotationPresent(JmsAnnoation.class)) {
                JmsAnnoation jmsAnnoation = jmsListener.getClass().getAnnotation(JmsAnnoation.class);
                JmsDestination jmsDestination = new JmsDestination();
                jmsDestination.setBeanName(beanName);
                jmsDestination.setName(jmsAnnoation.destination());
                jmsDestination.setQueue(jmsAnnoation.isQueue());
                jmsDestination.setAutoCommit(jmsAnnoation.autoCommit());
                jmsDestination.setFailureCount(jmsAnnoation.failureCount());
                list.add(jmsDestination);
            }
        }
        return list;
    }

    /****
     * 查询指定JMS目的地信息
     * @param destinationName
     * @return
     */
    @Override
    public List<JmsDestination> getDestination(String destinationName) {
        List<JmsDestination> list = new ArrayList<>();
        for (JmsDestination destination : this.getDestinations()) {
            if (destination.getName().equalsIgnoreCase(destinationName)) {
                list.add(destination);
            }
        }
        return list;
    }
}
